from django.conf import settings
from django.contrib.auth.hashers import make_password, check_password
from django.core.mail import send_mail
from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
import re


class RegisterView(APIView):
    """
    @ author:baisansui
    # date:2020-10-26
    用户注册:需要提供以下数据
        用户名、密码、确认密码、邮箱
    """

    def post(self, request):
        """
        {'username':['laowu'],'password1':['123'],'password2':['123'],'email':['laowu123@qq.com']}
        """
        username = request.data.get("username")
        password1 = request.data.get("password1")
        password2 = request.data.get("password2")
        email = request.data.get("email")

        # 判断数据的完整性
        if not all([username, password1, password2, email]):
            return Response({"msg": "数据不完整", "code": 400})

        # 正则验证邮箱
        ex_email = re.compile(r'.*@[a-zA-Z0-9]{2,3}.com')
        if not re.match(ex_email, email):
            return Response({"msg": "邮箱格式不正确", "code": 400})

        # 判断用户是否存在
        user_obj = User.objects.filter(username=username).first()
        if user_obj:
            return Response({"msg": "该用户已注册", "code": 400})

        # 两次密码验证
        if password1 == password2:
            # 构造数据
            user_data = {"username": username, "password": make_password(password1), "email": email}
            user_ser = UserSer(data=user_data)

            # 校验数据
            if user_ser.is_valid():
                user_ser.save()
                print(user_ser.data)
                subject = '美多商城会员注册'
                message = ''
                from_email = settings.EMAIL_FROM
                recipient_list = [email]
                html_message = "{},欢迎注册美多商城会员，请点击下方链接进行激活：<br /><a href='http://127.0.0.1:8000/web/active/?user_id={}'>点击激活会员</a>".format(
                    username, user_ser.data.get('id'))
                send_mail(subject, message, from_email, recipient_list, html_message=html_message)
                return Response({"msg": "注册成功", "code": 200})
            else:
                return Response({"error": user_ser.errors, "code": 400})
        else:
            return Response({"msg": "两次密码不一致", "code": 400})


class CheckUsernameView(APIView):

    def get(self, request):
        username = request.query_params.get('username')
        user_obj = User.objects.filter(username=username)
        if user_obj:
            return Response({"msg": "用户名已存在", "code": 400})
        else:
            return Response({"msg": "OK", "code": 200})


class ActiveView(APIView):

    def get(self, request):
        user_id = request.query_params.get('user_id')
        return Response({"msg": "OK"})
